﻿using System;
using System.Data;
using System.Data.OleDb;

namespace OurCouse.DBTask
{
    public class RegUserDBTask
    {
		/// <summary>
		/// 获取用户列表
		/// </summary>
		private const String SQL_GetRegUserList = "SELECT * FROM RegUser";
		private const String SQL_AddUser = "INSERT INTO RegUser ( UserName, UserPass ) VALUES ( @UserName, @UserPass )";
		private const String SQL_InitMoney = "INSERT INTO UserMoney ( UserName, CurrMoney ) VALUES ( @UserName, @CurrMoney )";
		private const String SQL_UserLogin = "SELECT * FROM RegUser WHERE UserName=@UserName AND UserPass=@UserPass";

		public DataSet GetRegUserList()
		{
			DataSet ds = null;

			// 创建数据连接
			OleDbConnection dbConn = DBConnectionFactory.Create();
			// 创建数据适配器
			OleDbDataAdapter dbAdp = new OleDbDataAdapter(SQL_GetRegUserList, dbConn);

			ds = new DataSet();
			dbAdp.Fill(ds, "RegUser");

			return ds;
		}

		public Boolean AddUser(string username,string password)
		{ 
			// 创建数据连接
			OleDbConnection dbConn = DBConnectionFactory.Create();
			// 声明数据库事务
			OleDbTransaction dbTranx = null;


			try
			{
				dbConn.Open();

				// 创建数据库事务
				dbTranx = dbConn.BeginTransaction();

				// 创建数据库命令
				OleDbCommand dbCmd0 = new OleDbCommand(SQL_AddUser, dbConn, dbTranx);
				OleDbCommand dbCmd1 = new OleDbCommand(SQL_InitMoney, dbConn, dbTranx);

				// 添加用户
				dbCmd0.Parameters.AddWithValue("@UserName", username);
				dbCmd0.Parameters.AddWithValue("@UserPass", password);
				dbCmd0.ExecuteNonQuery();

				// 初始化资金
				dbCmd1.Parameters.AddWithValue("@UserName", username);
				dbCmd1.Parameters.AddWithValue("@CurrMoney", 10.0f);
				dbCmd1.ExecuteNonQuery();

				//throw new Exception("我操，出错了!");

				dbTranx.Commit();
			}
			catch
			{
				if (dbTranx != null)
				{
					dbTranx.Rollback();
				}

				throw;
			}
			finally
			{
				dbConn.Close();
			}
			
			return true;
		}
    
		/// <summary>
		/// 用户登录
		/// </summary>
		public Boolean UserLogin(string username, string password)
		{
			// 创建数据连接
			OleDbConnection dbConn = DBConnectionFactory.Create();

			// 创建数据库命令
			OleDbCommand dbCmd = new OleDbCommand(SQL_UserLogin, dbConn);

			// 查询用户
			dbCmd.Parameters.AddWithValue("@UserName", username);
			dbCmd.Parameters.AddWithValue("@UserPass", password);

			dbConn.Open();

			OleDbDataReader dr = dbCmd.ExecuteReader();

			if (dr.Read())
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
}
